/**
 * 应用入口文件
 * 配置Express服务器和中间件
 */
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const { errorHandler } = require('./middleware/errorHandler');
const logger = require('./utils/logger');

// 导入路由
const authRoutes = require('./routes/authRoutes');
const taskRoutes = require('./routes/taskRoutes');
const pomodoroRoutes = require('./routes/pomodoroRoutes');
const financeRoutes = require('./routes/financeRoutes');
const noteRoutes = require('./routes/noteRoutes');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3000;

// 应用中间件
app.use(helmet());  // 安全HTTP头
app.use(cors());    // 启用CORS
app.use(morgan('combined', { stream: logger.stream }));  // HTTP请求日志
app.use(express.json());  // 解析JSON请求体
app.use(express.urlencoded({ extended: true }));  // 解析URL编码的请求体

// 使用路由
app.use('/api/auth', authRoutes);
app.use('/api/tasks', taskRoutes);
app.use('/api/pomodoros', pomodoroRoutes);
app.use('/api/finances', financeRoutes);
app.use('/api/notes', noteRoutes);

// 健康检查路由
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'OK', message: 'Service is running' });
});

// 404处理
app.use((req, res, next) => {
  res.status(404).json({ message: 'Resource not found' });
});

// 错误处理中间件
app.use(errorHandler);

// 启动服务器
app.listen(PORT, () => {
  logger.info(`Server running on port ${PORT}`);
});

module.exports = app; 